module(..., package.seeall)

require'zdc.node'
require'zdc.typeex'
require'zdc.dpl'
require'zdc.idutil'
require'zdc.idtree'

GimTR = {}
local GimTR_mt = {__metatable={}, __index=GimTR}
function MakeInhMT(ch)
	ch=ch or {}
	for _i,_j in pairs(GimTR) do
		ch[_i]=_j
	end
	return ch
end

function new(mt)
	local repo = setmetatable({idtr=zdc.idtree.new()}, mt or GimTR_mt)
	return repo
end

function GimTR:__tr_to_dpl(dal,tr,id)
	return tr.v
end

function GimTR:_delall(dal)
	self.idtr:_clear_all()
end
function GimTR:_get_info(dal)
	return self.idtr:_do_every(function (v) return print(v.pos,v.v) end)
end

--return dpl[,errmsg]
function GimTR:_add_dpl(dal,idlist,_,_,dpl)
	self.idtr:_add_pattern(idlist,dpl)
	return dpl
end
function GimTR:_add_dpl_ex(dal,kv,dpl)
	self.idtr:_add_pattern(kv.pat,dpl,kv.opt)
	return dpl
end

function GimTR:_get_svcdpl_by_id(dal,id)
	local dpl=self:_get_dpl_by_id(dal,id)
	if dpl then return dpl end
end

--return dpl[,errmsg]
function GimTR:_get_dpl_by_id(dal,id)
	if not id then return nil end
	local tr=self.idtr:_query(id)
	if tr then
		return self:__tr_to_dpl(dal,tr,id)
	end
end

function GimTR:_get_dpl_by_parent(dal,idparent)
	local m=self.map
	local idparent_=idparent .. '/*'
	local tr=self.idtr:_query(idparent_)
	if tr then
		return self:__tr_to_dpl(dal,tr,idparent_)
	end
end

--return {dpl1,dpl2,...}
function GimTR:_get_sub_dpls(dal,idparent)
	local re=self.idtr:_query_subs(idparent)
	if re then
		for k,v in ipairs(re) do
			re[k]=self:__tr_to_dpl(dal,v,idparent)
		end
	end
	return re
end

--when match call fun(dpl)
function GimTR:_do_every_dpl(dal,fun)
	return self.idtr:_do_every(function (v) return fun(self:__tr_to_dpl(dal,v)) end)
end
